package group2.beans;

import group2.core.database.DatabaseUtil;
import group2.core.entities.CamelUser;
import group2.core.UserLevel;
import java.io.Serializable;
import javax.ejb.Stateful;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

/** 
 * This bean is used to control the logins.
 * 
 * @author cnilsson
 */
@ManagedBean
@RequestScoped
@Stateful
public class LoginControllerBean implements Serializable{

    @ManagedProperty(value = "#{loginBackingBean}")
    private LoginBackingBean lbb;
    @ManagedProperty(value = "#{authSessionBean}")
    private AuthSessionBean asb;
    private CamelUser loggedInUser = null;
    private boolean loginSuccess = false;

    public void doLogin(ActionEvent e) {
        if (DatabaseUtil.getInstance().verifyPassword(lbb.getUserName(), lbb.getPassword())) {
            loggedInUser = DatabaseUtil.getInstance().findCamelUserByName(lbb.getUserName());

            FacesContext context = FacesContext.getCurrentInstance();
            HttpSession session =
                    (HttpSession) context.getExternalContext().getSession(true);
            session.setAttribute("username", loggedInUser);
            this.loginSuccess = true;
            postAuth();
            adminAuth();
            setAuthedUsed();
        } else {
            loggedInUser = null;
        }
    }
    //Maybe not the best way to do this

    public String doLogout() {
        this.loggedInUser = null;

        FacesContext fCtx = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);
        session.invalidate();
        return "dunes.jsf";
    }

    public String navigate() {
        if (loginSuccess) {
            return "onLoginSuccess";
        } else {
            return "onLoginFailure";
        }
    }

    public void postAuth() {
        asb.setPostAuth(!loggedInUser.getUserLevel().equals(UserLevel.USER));
    }

    public void adminAuth() {
        asb.setAdminAuth(loggedInUser.getUserLevel().equals(UserLevel.ADMIN));
    }
    public void setAuthedUsed()
    {
        asb.setLoggedInUser(this.loggedInUser);
    }

    public LoginBackingBean getLbb() {
        return lbb;
    }

    public void setLbb(LoginBackingBean lbb) {
        this.lbb = lbb;
    }

    public CamelUser getLoggedInUser() {
        return loggedInUser;
    }

    public AuthSessionBean getAsb() {
        return asb;
    }

    public void setAsb(AuthSessionBean asb) {
        this.asb = asb;
    }

    /** Creates a new instance of LoginControllerBean */
    public LoginControllerBean() {
    }
}
